What is Call By Value in C# ?
1390
16-Nov-2020
Aryan Kumar
06-Jun-2023Call by value is a method of passing arguments to a function in C#. When a value is passed by value, a copy of the value is made and passed to the function. Any changes made to the value inside the function do not affect the original value.
For example, the following code shows how to pass an integer value to a function by value:
C#
In this example, the value 10 is copied to the local variable value inside the myFunction() function. When the value variable is multiplied by 2, the change only affects the local variable. The original value of 10 is not affected.
Call by value is the default way of passing arguments to functions in C#. It is a simple and efficient way of passing data to functions. However, it can sometimes be inconvenient if you want to make changes to the original value inside the function.
In these cases, you can use call by reference. Call by reference passes a reference to the value to the function. This means that any changes made to the value inside the function will affect the original value.
For example, the following code shows how to pass an integer value to a function by reference:
C#
In this example, the value variable is passed by reference to the myFunction() function. When the value variable is multiplied by 2, the change affects the original value. The value 20 is printed to the console.
Call by reference can be more convenient than call by value, but it can also be more dangerous. If you accidentally change the value of a variable inside a function, you may not realize that you have done so. This can lead to bugs in your code.
It is important to choose the right method of passing arguments to functions based on your specific needs. Call by value is a good choice for most cases, but call by reference can be useful when you need to make changes to the original value.
Rahul Roi
16-Nov-2020Into the C#, the value-type parameters are that pass a copy of the original value to the function rather than reference. That does not modify the original value. The change made in the passed value does not alter the actual value. Into the following example, we have a pass value during the function call.
Example :-
Output :-